const Koa=require('koa2');
const app=new Koa();
const sleep=ms=>new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve();
    },ms);
});
const responseTime=async (ctx,next)=>{
    console.log('responseTime start');
    let start=Date.now();
    await next();
    let es=Date.now()-start;
    console.log('responseTime end:',es);
    ctx.set('X-ResponseTime',es);
};

app.use(async (ctx,next)=>{
    try{
        await next();
    }catch(err){
        console.log('Error:',err);
        ctx.status=500;
        ctx.body='Internal Server Error!!!';
    }
});

app.use(responseTime);

app.use(async (ctx,next)=>{
    console.log('Status');
    ctx.status=200;
    await next();//
    console.log('Status End');
});

app.use(async ctx=>{
    await sleep(500);
    console.log('Body');
    ctx.body='OK!!';
    console.log('Body End');
    throw new Error('Set body error!');
});


app.listen(3002,()=>{
    console.log('\n\nPort 3002',new Date().toLocaleTimeString());
});
